/*
 *  Author : Thanh Pham
 *  Create on : 14/9/2013 , 5:05 PM
 */
package DAO;

import java.sql.Connection;
import java.sql.ResultSet;



import java.sql.SQLException;
import java.sql.Statement;

import ConnectMng.ConnectMng;
import Entity.Users;

public class LoginDAO {
    private static Connection conn;
    private static Statement stmt;
    private static ResultSet rs;
	
	public static Users checkUsers(Users user) throws SQLException{
		try{
			String sql = "SELECT * FROM Users WHERE username = '"+user.getUsername()+"' "
					+ "AND password = '"+user.getPassword()+"'";
			System.out.println(sql);
			conn = ConnectMng.getConnectionSQLSERVER();
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			
			while(rs.next()){
				user.setUserId(rs.getInt("userId"));
				user.setEmail(rs.getString("email"));
				user.setRoles(rs.getString("roles"));
			}

		}catch(Exception ex){
			System.out.println(" Class LoginDAO, Method: checkUsers, error: "+ex.getMessage());
		}finally{
			if(rs != null){
				rs.close();
			}
			if(stmt != null){
				stmt.close();
			}
			if(conn != null){
				conn.close();
			}
		}
		return user;
	}
	
	public static Users getUsers(String userName) throws SQLException{
		Users user = new Users();
		try{
			String sql = "SELECT * FROM Users WHERE userName = '"+userName+"'";
			System.out.println(sql);
			conn = ConnectMng.getConnectionSQLSERVER();
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			
			while(rs.next()){
				user.setUserId(rs.getInt("userId"));
				user.setUsername(rs.getString("username"));
				user.setPassword(rs.getString("password"));
				user.setEmail(rs.getString("email"));
				user.setRoles(rs.getString("roles"));
			}

		}catch(Exception ex){
			System.out.println(" Class LoginDAO, Method: checkUsers, error: "+ex.getMessage());
		}finally{
			if(rs != null){
				rs.close();
			}
			if(stmt != null){
				stmt.close();
			}
			if(conn != null){
				conn.close();
			}
		}
		return user;
	}	
		
	public static void main(String [] args) throws SQLException{
		Users user = new Users();
		user.setUsername("thanhpv1");
		user.setPassword("12345678");
		user = LoginDAO.checkUsers(user);
		System.out.println(user.getUserId());
		
		Users getuser = LoginDAO.getUsers("thanhpv1");
		System.out.println(getuser.getRoles());
	}
}
